/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

class MyPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject)
    } catch (e) {
      this.reject(e)
    }
  }
  // promise状态
  status = PENDING;
  value = undefined
  reason = undefined
  // 处理异步情况，存储成功和失败回调
  /*   successCallback = undefined
    failCallback = undefined */
  // 数组是因为同一个promise可以调用多次then方法
  successCallback = []
  failCallback = []
  resolve = (value) => {
    // console.log(this);
    // 如果状态不是等待 阻止程序向下执行
    if (this.status !== PENDING) return
    // 将状态更改为成功
    this.status = FULFILLED
    // 保存成功之后的值，因为要在then中拿到
    this.value = value
    // 处理异步情况
    // 判断成功回调是否存在 如果存在调用
    // this.successCallback && this.successCallback(this.value)
    while (this.successCallback.length) this.successCallback.shift()()
  }
  reject = (reason) => {
    if (this.status !== PENDING) return
    // 将状态更改为失败
    this.status = REJECTED
    // 保存失败之后的原因
    this.reason = reason
    // 处理异步情况
    // 判断失败回调是否存在 如果存在调用
    // this.failCallback && this.failCallback(this.reason)
    while (this.failCallback.length) this.failCallback.shift()(this.reason)
  }
  then(successCallback, failCallback) {
    // then方法可以进行链式调用，返回一个新的promise
    successCallback = successCallback ? successCallback : value => value
    failCallback = failCallback ? failCallback : reason => { throw reason }
    let promise2 = new MyPromise((resolve, reject) => {
      // 执行器，立即执行
      if (this.status === FULFILLED) {
        // 变成异步代码，等所有同步代码执行结束后才执行，获取到promise2
        setTimeout(() => {
          try {
            // x为这个promise的返回值
            let x = successCallback(this.value)
            // resolve(x)
            // 判断x的值是普通值还是promise对象
            // 如果是普通值，直接调用resolve
            // 如果是promise对象，查看promise对象返回的结果
            // 再根据promise对象返回的结果 决定调用resolve 还是reject
            // promise2参数用来判断是否自己调用自己
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
      } else if (this.status === REJECTED) {
        // failCallback(this.reason)
        // 变成异步代码，等所有同步代码执行结束后才执行，获取到promise2
        setTimeout(() => {
          try {
            // x为这个promise的返回值
            let x = failCallback(this.reason)
            // resolve(x)
            // 判断x的值是普通值还是promise对象
            // 如果是普通值，直接调用resolve
            // 如果是promise对象，查看promise对象返回的结果
            // 再根据promise对象返回的结果 决定调用resolve 还是reject
            // promise2参数用来判断是否自己调用自己
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        }, 0)
      } else {
        // 如果是异步代码 settimeout
        // 等待 
        // 将成功回调和失败回调存储起来
        /*  this.successCallback = successCallback
         this.failCallback = failCallback */
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              // x为这个promise的返回值
              let x = successCallback(this.value)
              // resolve(x)
              // 判断x的值是普通值还是promise对象
              // 如果是普通值，直接调用resolve
              // 如果是promise对象，查看promise对象返回的结果
              // 再根据promise对象返回的结果 决定调用resolve 还是reject
              // promise2参数用来判断是否自己调用自己
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          }, 0)
        })
        this.failCallback.push(() => {
          // failCallback()
          setTimeout(() => {
            try {
              // x为这个promise的返回值
              let x = failCallback(this.reason)
              // resolve(x)
              // 判断x的值是普通值还是promise对象
              // 如果是普通值，直接调用resolve
              // 如果是promise对象，查看promise对象返回的结果
              // 再根据promise对象返回的结果 决定调用resolve 还是reject
              // promise2参数用来判断是否自己调用自己
              resolvePromise(promise2, x, resolve, reject)
            } catch (e) {
              reject(e)
            }
          }, 0)
        })
      }
    })
    return promise2
  }
  catch(failCallback) {
    return this.then(undefined, failCallback)
  }
  finally(callback) {
    return this.then((value) => {
      return MyPromise.resolve(callback()).then(() => value)
     /*  callback()
      return value */
    }, (reason) => {
      return MyPromise.resolve(callback()).then(() => {throw reason})
      /* callback()
      throw reason */
    })
  }
  static all(array) {
    let result = []
    let index = 0

    return new MyPromise((resolve, reject) => {
      function addData(key, value) {
        result[key] = value
        index++
        if (index === array.length) {
          resolve(result)
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i]
        if (current instanceof MyPromise) {
          // promise对象
          current.then(value => addData(i, value), reason => reject(reason))
        } else {
          // 普通值
          addData(i, array[i])
        }
      }
      // resolve(result)
    })
  }
  static resolve(value) {
    if (value instanceof MyPromise) return value
    return new Promise(resolve => resolve(value))
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  if (promise2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
  }
  if (x instanceof MyPromise) {
    // x是promise对象
    // x.then(value => resolve(value), reason => reject(reason))
    x.then(resolve, reject)
  } else {
    // x是普通值
    resolve(x)
  }
}
module.exports = MyPromise